package com.example.config;

import com.drew.lang.annotations.NotNull;
import com.example.demo.Student;
import com.example.impl.StudentMapper;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@ServerEndpoint("/websocket/{id}")
public class WebSocketServer {



    /**
     * 当前在线人数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放每个客户端对应的 WebSocketServer 对象
     */
//    private static CopyOnWriteArrayList<WebSocketServer> webSocketServers = new CopyOnWriteArrayList<>();

    /**
     * 存放每个客户端对应的 WebSocketServer 对象
     */
    private static Map<String, Session> webSocketServerMap = new ConcurrentHashMap<>();
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        // 加入集合中
//       webSocketServers.add(this);
        webSocketServerMap.put(session.getPathParameters().get("id"), session);
        // 在线人数+1
        int count = onlineCount.incrementAndGet();
        log.info("有新的窗口开始监听：, 当前在线人数为：{}",webSocketServerMap.size());
    }

    /**
     * 收到客服端消息后调用的方法
     *
     * @param message 客服端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口：{}, 消息内容：{}", message, session.getMessageHandlers());
        Map<String, String> pathParameters = session.getPathParameters();
        String id = pathParameters.get("id");
        System.out.println(id);
        if (!StringUtils.isNullOrEmpty(message)) {
            // 进行业务逻辑处理
        }
        ServiceImpl serviceImpl = (ServiceImpl) AppContextUtil.getBean("ServiceImpl");
        Student student = serviceImpl.getStudent();
        System.out.println(student);
        // 群发消息
//               for (WebSocketServer webSocketServer : getWebSocketServers()) {
//                   webSocketServer.sendMessage("1111");
//               }
    }


    /**
     * 发生错误时调用的方法
     */
    @OnError
    public void onError(Session session, @NotNull Throwable throwable) {
        log.error("发生错误");
        throwable.printStackTrace();
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketServerMap.remove(session.getPathParameters().get("id"));
        // 在线人数-1
        int count = onlineCount.decrementAndGet();
        log.info("释放的sid为：{}");
        log.info("有一连接关闭！当前在线人数为：{}", count);
    }

    /**
     * 实现服务器主动推送消息
     *
     * @param message 消息内容
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
            log.info("message:{}", message);
        } catch (IOException e) {
            log.error("websocket IO Exception");
            e.printStackTrace();
        }
    }


    public void sendMessage(String message, List<String> userId) {
        for (String s : userId) {
            Session session = webSocketServerMap.get(s);
            if (Objects.nonNull(session)) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}